from flask import Flask, request, jsonify
from flask_cors import CORS
import zipfile
import os
import tempfile
import shutil
from pathlib import Path

app = Flask(__name__)
CORS(app)

# ✅ 固定本地路径（无需用户交互）
LOCAL_TARGET_ROOT = r"C:\\Users\\Administrator\\Desktop\\01"  # 修改为你想要的固定路径

os.makedirs(LOCAL_TARGET_ROOT, exist_ok=True)

@app.route('/api/local-receive', methods=['POST'])
def local_receive():
    """接收前端传来的 ZIP 并自动解压到固定路径"""
    try:
        if 'file' not in request.files:
            return jsonify({'error': '没有文件'}), 400

        file = request.files['file']
        if not file.filename.endswith('.zip'):
            return jsonify({'error': '只支持 ZIP 文件'}), 400

        # 保存临时 ZIP
        temp_dir = tempfile.mkdtemp()
        zip_path = os.path.join(temp_dir, 'temp.zip')
        file.save(zip_path)

        # 解压到固定路径
        with zipfile.ZipFile(zip_path, 'r') as zf:
            zf.extractall(LOCAL_TARGET_ROOT)

        # 清理
        shutil.rmtree(temp_dir, ignore_errors=True)

        return jsonify({'message': '文件夹已自动解压到本地', 'path': LOCAL_TARGET_ROOT})

    except Exception as e:
        return jsonify({'error': str(e)}), 500


if __name__ == '__main__':
    print(f"📥 本地接收器已启动，自动写入路径：{LOCAL_TARGET_ROOT}")
    app.run(host='127.0.0.1', port=5001, debug=False)